﻿Type.registerNamespace('MS.InformationManagement.MailDeliveryConfig');
MS.InformationManagement.MailDeliveryConfig.FetchTimeout = null;

MS.InformationManagement.MailDeliveryConfig.Initialize = function (deliveryMeansControlID, mailWeightControlID, deliveryCostControlID, spinnerControlID, isLocalDeliveryControlID, isNationalDeliveryControlID
, submitButtonID) {
    MS.InformationManagement.Services.DeliveryMeansService.set_path('/sites/docs/' + MS.InformationManagement.Services.DeliveryMeansService.get_path());
    var weightTextBox = $('#' + mailWeightControlID);
    var deliveryCostTextBox = $('#' + deliveryCostControlID);
    var deliveryMeanDropdown = $('#' + deliveryMeansControlID);
    var spinner = $('#' + spinnerControlID);
    var localRadioButton = $('#' + isLocalDeliveryControlID);
    var nationalRadioButton = $('#' + isNationalDeliveryControlID);
    var submitButton = $('#' + submitButtonID);

    weightTextBox.bind("propertychange keyup input paste",
        function (event) {
            MS.InformationManagement.MailDeliveryConfig.FetchDeliveryCost(weightTextBox, deliveryCostTextBox, deliveryMeanDropdown, spinner, localRadioButton, nationalRadioButton
                , submitButton);
        }
    );
    deliveryMeanDropdown.change(function () {
        MS.InformationManagement.MailDeliveryConfig.FetchDeliveryCost(weightTextBox, deliveryCostTextBox, deliveryMeanDropdown, spinner, localRadioButton, nationalRadioButton
                , submitButton);
    });
    localRadioButton.click(function () {
        MS.InformationManagement.MailDeliveryConfig.FetchDeliveryCost(weightTextBox, deliveryCostTextBox, deliveryMeanDropdown, spinner, localRadioButton, nationalRadioButton
                , submitButton);

    });
    nationalRadioButton.click(function () {
        MS.InformationManagement.MailDeliveryConfig.FetchDeliveryCost(weightTextBox, deliveryCostTextBox, deliveryMeanDropdown, spinner, localRadioButton, nationalRadioButton
                , submitButton);
    });
}

MS.InformationManagement.MailDeliveryConfig.InitializeMailBagGrid = function (mailbagGridControlID, totalDeliveryCostControlID, areaAutoCompleteControlID, saveDeliveriesControlID) {
    MS.InformationManagement.Services.DeliveryMeansService.set_path('/sites/docs/' + MS.InformationManagement.Services.DeliveryMeansService.get_path());
    MS.InformationManagement.Services.AreaService.set_path('/sites/docs/' + MS.InformationManagement.Services.AreaService.get_path());
    var mailbagGrid = $('#' + mailbagGridControlID);
    var mailbagGridParent = mailbagGrid.parent();
    var totalDeliveryCostTextBox = $('#' + totalDeliveryCostControlID);
    var saveDeliveriesButton = $('#' + saveDeliveriesControlID);
    var areaAutocompleteTextBox = $('#' + areaAutoCompleteControlID);

    totalDeliveryCostTextBox.data('float-value', 0);
    mailbagGridParent.ajaxloader({ fullscreen: true, baseurl: '/sites/docs', autoshow: false });

    mailbagGrid.find('div.form-container').each(function () {
        MS.InformationManagement.MailDeliveryConfig.InitializeGridEditControls($(this), totalDeliveryCostTextBox, mailbagGridParent);
    });

    MS.InformationManagement.MailDeliveryConfig.SaveDeliveries(mailbagGrid, mailbagGridParent, saveDeliveriesButton);
    MS.InformationManagement.MailDeliveryConfig.SetupAreaAutoComplete(areaAutocompleteTextBox);


}

MS.InformationManagement.MailDeliveryConfig.SetupAreaAutoComplete = function (areaAutocompleteTextBox) {
    areaAutocompleteTextBox.autocomplete(
        {
            source: function (request, response) {
                areaAutocompleteTextBox.attr('disabled', 'disabled');
                MS.InformationManagement.Services.AreaService.GetAreas(
                    request.term,
                    MS.InformationManagement.MailDeliveryConfig.OnSuccess4,
                    MS.InformationManagement.MailDeliveryConfig.OnError4,
                    { response: response, areaAutocompleteTextBox: areaAutocompleteTextBox }
                );
            }
            , minLength: 3
        }
    );
}

MS.InformationManagement.MailDeliveryConfig.OnSuccess4 = function (result, userstate) {
    userstate.response($.map(result, function (item) {
        return {
            label: item.Title,
            value: item.Title
        }
    }));
    userstate.areaAutocompleteTextBox.attr('disabled', '');
}

MS.InformationManagement.MailDeliveryConfig.OnError4 = function (exception, userstate) {
    userstate.areaAutocompleteTextBox.attr('disabled', '');
    MS.InformationManagement.Common.ShowStatus('Ha ocurrido una excepción mientras se procesaba su peticion: ' + exception.get_message(), 'red', 6000);
}

MS.InformationManagement.MailDeliveryConfig.SaveDeliveries = function (mailbagGrid, mailbagGridParent, saveDeliveriesButton) {
    saveDeliveriesButton.click(function () {
        saveDeliveriesButton.attr('disabled', 'disabled');
        mailbagGridParent.ajaxloader('show');
        var deliveries = new Array();
        mailbagGrid.find('div.form-container').each(function () {
            MS.InformationManagement.MailDeliveryConfig.PopulateEntity($(this), deliveries);
        });

        MS.InformationManagement.Services.DeliveryMeansService.SaveDeliveries(
            deliveries,
            MS.InformationManagement.MailDeliveryConfig.OnSuccess3,
            MS.InformationManagement.MailDeliveryConfig.OnError3,
            {
                saveDeliveriesButton: saveDeliveriesButton,
                mailbagGridParent: mailbagGridParent
            }
        );
    });
}

    MS.InformationManagement.MailDeliveryConfig.PopulateEntity = function (deliveryControlContainer, deliveries) {
        var weightTextBox = deliveryControlContainer.find('input[id*="txtbWeight"]');
        var deliveryCostTextBox = deliveryControlContainer.find('input[id*="txtbCost"]');
        var deliveryMeanDropdown = deliveryControlContainer.find('select[id*="ddlDeliveryMean"]');
        var deliveryZone = deliveryControlContainer.find('select[id*="ddlZona"]');
        var localRadioButton = deliveryControlContainer.find('input[id*="rdbIsLocal"]');
        var nationalRadioButton = deliveryControlContainer.find('input[id*="rdbIsNational"]');
        var documentIdControl = deliveryControlContainer.find('input[id*="hdfId"]');
        var documentNumberControl = deliveryControlContainer.find('input[id*="hdfDocNumber"]');
        var libraryNameControl = deliveryControlContainer.find('input[id*="hdfLibraryName"]');
        var isCopyControl = deliveryControlContainer.find('input[id*="hdfIsCopy"]');
        var itemIdControl = deliveryControlContainer.find('input[id*="hdfItemId"]');

        if (deliveryCostTextBox.data('float-value') === 0) { return; }

        var itemId = 0;
        if (itemIdControl.val() != '') {
            itemId = parseInt(itemIdControl.val());
        }

        var delivery = {
            DocumentNumber: documentNumberControl.val(),
            DocumentId: parseInt(documentIdControl.val()),
            DeliveryMeanId: parseInt(deliveryMeanDropdown.val()),
            LibraryName: libraryNameControl.val(),
            Weight: parseFloat(weightTextBox.val()),
            DeliveryCost: deliveryCostTextBox.data('float-value'),
            IsLocalDelivery: localRadioButton.attr('checked'),
            IsNationalDelivery: nationalRadioButton.attr('checked'),
            IsCopy: isCopyControl.val() == "True",
            ListItemId: itemId,
            DeliveryZone: parseInt(deliveryZone.val())
        };

        deliveries.push(delivery);
    }

MS.InformationManagement.MailDeliveryConfig.InitializeGridEditControls = function (deliveryInfoControlContainer, totalDeliveryCostTextBox, mailbagGridParent) {
    var weightTextBox = deliveryInfoControlContainer.find('input[id*="txtbWeight"]');
    var deliveryCostTextBox = deliveryInfoControlContainer.find('input[id*="txtbCost"]');
    var deliveryMeanDropdown = deliveryInfoControlContainer.find('select');
    var localRadioButton = deliveryInfoControlContainer.find('input[id*="rdbIsLocal"]');
    var nationalRadioButton = deliveryInfoControlContainer.find('input[id*="rdbIsNational"]');

    deliveryCostTextBox.data('float-value', 0);

    weightTextBox.bind("propertychange keyup input paste", function (event) {
        MS.InformationManagement.MailDeliveryConfig.FetchDeliveryCost2(weightTextBox, deliveryCostTextBox, deliveryMeanDropdown, localRadioButton, nationalRadioButton
        , totalDeliveryCostTextBox, mailbagGridParent);
    });
    deliveryMeanDropdown.change(function () {
        MS.InformationManagement.MailDeliveryConfig.FetchDeliveryCost2(weightTextBox, deliveryCostTextBox, deliveryMeanDropdown, localRadioButton, nationalRadioButton
        , totalDeliveryCostTextBox, mailbagGridParent)
    });
    localRadioButton.click(function () {
        MS.InformationManagement.MailDeliveryConfig.FetchDeliveryCost2(weightTextBox, deliveryCostTextBox, deliveryMeanDropdown, localRadioButton, nationalRadioButton
        , totalDeliveryCostTextBox, mailbagGridParent)
    });
    nationalRadioButton.click(function () {
        MS.InformationManagement.MailDeliveryConfig.FetchDeliveryCost2(weightTextBox, deliveryCostTextBox, deliveryMeanDropdown, localRadioButton, nationalRadioButton
        , totalDeliveryCostTextBox, mailbagGridParent)
    });
}

MS.InformationManagement.MailDeliveryConfig.FetchDeliveryCost = function (weightTextBox, deliveryCostTextBox, deliveryMeanDropdown, spinner, localRadioButton, nationalRadioButton
        , submitButton) {
    clearTimeout(MS.InformationManagement.MailDeliveryConfig.FetchTimeout);
    MS.InformationManagement.MailDeliveryConfig.FetchTimeout = setTimeout(
        function () {
            if (deliveryMeanDropdown.val() == '' || weightTextBox.val() == '') {
                MS.InformationManagement.Common.ShowStatus('Debe seleccionar un medio de envio o ingresar un peso válido', 'yellow', 6000);
                return;
            }
            submitButton.attr('disabled', 'disabled');
            spinner.addClass('inline');
            weightTextBox.attr('readonly', 'readonly');
            deliveryMeanDropdown.attr('readonly', 'readonly');

            MS.InformationManagement.Services.DeliveryMeansService.GetDeliveryMeanConfig(
                deliveryMeanDropdown.val()
                , weightTextBox.val()
                , MS.InformationManagement.MailDeliveryConfig.OnSuccess
                , MS.InformationManagement.MailDeliveryConfig.OnError,
                {
                    weightTextBox: weightTextBox,
                    deliveryMeanDropdown: deliveryMeanDropdown,
                    deliveryCostTextBox: deliveryCostTextBox,
                    spinner: spinner,
                    submitButton: submitButton,
                    localRadioButton: localRadioButton,
                    nationalRadioButton: nationalRadioButton
                }
            );
        }
        , 1000);
}

MS.InformationManagement.MailDeliveryConfig.FetchDeliveryCost2 = function (weightTextBox, deliveryCostTextBox, deliveryMeanDropdown, localRadioButton, nationalRadioButton
        , totalDeliveryCostTextBox, mailbagGridParent) {
    clearTimeout(MS.InformationManagement.MailDeliveryConfig.FetchTimeout);
    MS.InformationManagement.MailDeliveryConfig.FetchTimeout = setTimeout(
        function () {
            if (deliveryMeanDropdown.val() == '' || weightTextBox.val() == '') {
                MS.InformationManagement.Common.ShowStatus('Debe seleccionar un medio de envio o ingresar un peso válido', 'yellow', 6000);
                return;
            }
            if (localRadioButton.attr('checked') == '' && nationalRadioButton.attr('checked') == '') {
                MS.InformationManagement.Common.ShowStatus('Debe seleccionar una localidad de envío', 'yellow', 6000);
                return;
            }
            mailbagGridParent.ajaxloader('show');
            MS.InformationManagement.Services.DeliveryMeansService.GetDeliveryMeanConfig(
                deliveryMeanDropdown.val()
                , weightTextBox.val()
                , MS.InformationManagement.MailDeliveryConfig.OnSuccess2
                , MS.InformationManagement.MailDeliveryConfig.OnError2,
                {
                    deliveryCostTextBox: deliveryCostTextBox,
                    totalDeliveryCostTextBox: totalDeliveryCostTextBox,
                    mailbagGridParent: mailbagGridParent,
                    localRadioButton: localRadioButton,
                    nationalRadioButton: nationalRadioButton
                }
            );

        }
        , 1000
    );
}

MS.InformationManagement.MailDeliveryConfig.OnSuccess3 = function (result, userstate) {
    userstate.mailbagGridParent.ajaxloader('hide');
    MS.InformationManagement.Common.ShowStatus('Los documentos seleccionados han sido configurados exitosamente', 'green', 6000);
    var pos = $('#pageStatusBar').offset();
    $('#s4-workspace').animate({ scrollTop: pos.top });
    RefreshPage();
}
MS.InformationManagement.MailDeliveryConfig.OnError3 = function (exception, userstate) {
    userstate.mailbagGridParent.ajaxloader('hide');
    userstate.saveDeliveriesButton.attr('disabled', '');
    MS.InformationManagement.Common.ShowStatus('Ha ocurrido una excepción mientras se procesaba su peticion: ' + exception.get_message(), 'red', 6000);
    var pos = $('#pageStatusBar').offset();
    $('#s4-workspace').animate({ scrollTop: pos.top });
}


MS.InformationManagement.MailDeliveryConfig.OnSuccess2 = function (result, userstate) {
    userstate.mailbagGridParent.ajaxloader('hide');

    if (result == null || result == '') {
        MS.InformationManagement.Common.ShowStatus('No existe configuración de costos para el medio de envio seleccionado y el peso ingresado.', 'yellow', 6000);
        return;
    }

    var currentDeliveryCost = null;
    var cumulativeDeliveryCost = (userstate.totalDeliveryCostTextBox.data('float-value'));
    var deliveryLocation = '';

    if (userstate.localRadioButton.attr('checked') == true) { deliveryLocation = 'local'; }
    if (userstate.nationalRadioButton.attr('checked') == true) { deliveryLocation = 'national'; }

    cumulativeDeliveryCost = cumulativeDeliveryCost - userstate.deliveryCostTextBox.data('float-value');

    if (deliveryLocation == 'local') {
        userstate.deliveryCostTextBox.data('float-value', result.LocalDeliveryCost);
        currentDeliveryCost = result.LocalDeliveryCost;
        userstate.deliveryCostTextBox.val($.format.number(result.LocalDeliveryCost, '#,###.##00'));
    }
    if (deliveryLocation == 'national') {
        userstate.deliveryCostTextBox.data('float-value', result.NationalDeliveryCost);
        currentDeliveryCost = result.NationalDeliveryCost;
        userstate.deliveryCostTextBox.val($.format.number(result.NationalDeliveryCost, '#,###.##00'));
    }

    cumulativeDeliveryCost = cumulativeDeliveryCost + currentDeliveryCost;
    userstate.totalDeliveryCostTextBox.data('float-value', cumulativeDeliveryCost);
    userstate.totalDeliveryCostTextBox.val($.format.number(cumulativeDeliveryCost, '#,###.##00'));
}

MS.InformationManagement.MailDeliveryConfig.OnError2 = function (exception, userstate) {
    userstate.mailbagGridParent.ajaxloader('hide');
    MS.InformationManagement.Common.ShowStatus('Ha ocurrido una excepción mientras se procesaba su peticion: ' + exception.get_message(), 'red', 6000);
}

MS.InformationManagement.MailDeliveryConfig.OnSuccess = function (result, userstate) {
    userstate.spinner.removeClass('inline');
    userstate.weightTextBox.attr('readonly', '');
    userstate.deliveryMeanDropdown.attr('readonly', '');

    if (result == null || result == '') {
        MS.InformationManagement.Common.ShowStatus('No existe configuración de costos para el medio de envio seleccionado y el peso ingresado.', 'yellow', 6000);
        return;
    }
    userstate.submitButton.attr('disabled', '');
    var deliveryLocation = '';
    if (userstate.localRadioButton.attr('checked') == true) { deliveryLocation = 'local'; }
    if (userstate.nationalRadioButton.attr('checked') == true) { deliveryLocation = 'national'; }
    if (deliveryLocation == 'local') { userstate.deliveryCostTextBox.val($.format.number(result.LocalDeliveryCost, '#,###.##00')); }
    if (deliveryLocation == 'national') { userstate.deliveryCostTextBox.val($.format.number(result.NationalDeliveryCost, '#,###.##00')); }
}

MS.InformationManagement.MailDeliveryConfig.OnError = function (exception, userstate) {
    userstate.spinner.removeClass('inline');
    userstate.weightTextBox.attr('readonly', '');
    userstate.deliveryMeanDropdown.attr('readonly', '');
    MS.InformationManagement.Common.ShowStatus('Ha ocurrido una excepción mientras se procesaba su peticion: ' + exception.get_message(), 'red', 6000);
}